package com.liruo.apt;

import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;

/**
 * @Author:liruo
 * @Date:2023-10-17-22:24:06
 * @Desc
 */
@SupportedAnnotationTypes("com.liruo.apt.Data")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class DataProcessor extends AbstractProcessor {
  /**
   * 抽象语法树
   */
  private JavacTrees trees;
  /**
   * AST
   */
  private TreeMaker treeMaker;
  /**
   * 标识符
   */
  private Names names;

  /**
   * 日志处理
   */
  private Messager messager;

  private Filer filer;

  public DataProcessor() {
  }

  public synchronized void init(ProcessingEnvironment processingEnvironment) {
    super.init(processingEnvironment);
    trees = JavacTrees.instance(processingEnv);
    Context context =  ((JavacProcessingEnvironment)processingEnv).getContext();
    treeMaker = TreeMaker.instance(context);
    names = Names.instance(context);
    filer = processingEnvironment.getFiler();
    messager = processingEnvironment.getMessager();
  }

  /**
   * @param annotations the annotation types requested to be processed
   * @param roundEnv  environment for information about the current and prior round
   */
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    roundEnv.getElementsAnnotatedWith(Data.class).stream()
        .map(element -> trees.getTree(element))
        .forEach(tree -> {
          //是demo9 bug2, 但是不能说是java9的, 而是写的注解处理器有问题
          treeMaker.pos = tree.pos;
          tree.accept(new DataTreeTranslator(
              messager,
              treeMaker,
              names
          ));
        });
    return true;
  }

}
